import Contextmenu from '@/components/Contextmenu'
import { createApp } from 'vue'
let vNodeDom = null
const handleContextMenu = (event, binding = {}) => {
    const { beforeContextMenu, menuList, handleClick } = binding
    // 没有菜单或者target验证不通过
    if ((!menuList || menuList.length == 0) || (beforeContextMenu && !beforeContextMenu(event))) {
        return
    }
    // 阻止默认的右键菜单
    event.preventDefault();

    const showMenuList = menuList.filter(item => {
        // 布尔值
        if (typeof (item.hidden) === "boolean") {
            return !item.hidden
        }
        // 函数
        if (Object.prototype.toString.call(item.hidden) === '[object Function]') {
            return !item.hidden()
        }
        return true
    })
    // 创建自定义菜单组件 将组件添加到body元素上
    const menu = createApp(Contextmenu, {
        left: event.clientX,
        top: event.clientY,
        menuList: showMenuList,
        event,
        handleClick
    })
    if (!vNodeDom) {
        // 单例确保只有一个右弹框
        vNodeDom = document.createElement('div')
        document.body.appendChild(vNodeDom)
    }
    const vm = menu.mount(vNodeDom)
    const closeMenu = () => {
        menu.unmount()
        document.body.removeEventListener('click', closeMenu)
    }
    document.body.addEventListener('click', closeMenu)
}

// 定义自定义指令
const contextmenu = {
    created(el, binding, vnode, prevVnode) {
        // 添加contextmenu事件监听
        el.addEventListener('contextmenu', (event) => { handleContextMenu(event, binding.value) });
    },
    beforeUnmount() {
        // // 取消contextmenu事件监听
        // el.removeEventListener('contextmenu', handleContextMenu);
        if(vNodeDom){
            document.body.removeChild(vNodeDom);
            vNodeDom = null;
        }
       
    }
}

export default contextmenu